"""
TTS服务管理器
整合所有语音合成功能
"""

import asyncio
from typing import Dict, List, Optional, Any
from ..tts.base import TTSEngine, TTSRequest, TTSResponse, VoiceProfile
from ..tts.pyttsx3_engine import Pyttsx3Engine
from ..tts.audio_converter import AudioConverter, AudioProcessor
from ..tts.voice_controller import VoiceController, VoiceSettings


class TTSService:
    """TTS服务管理器"""
    
    def __init__(self):
        self._engines: Dict[str, TTSEngine] = {}
        self._current_engine: Optional[TTSEngine] = None
        self._current_engine_name: Optional[str] = None
        self._converter = AudioConverter()
        self._processor = AudioProcessor()
        self._voice_controller = VoiceController()
        self._initialized = False
    
    async def initialize(self) -> bool:
        """初始化TTS服务"""
        try:
            # 初始化pyttsx3引擎
            pyttsx3_engine = Pyttsx3Engine()
            if await pyttsx3_engine.initialize():
                self._engines['pyttsx3'] = pyttsx3_engine
                self._current_engine = pyttsx3_engine
                self._current_engine_name = 'pyttsx3'
            
            # 可以在这里添加其他引擎
            # 如：espeak_engine = EspeakEngine()
            # if await espeak_engine.initialize():
            #     self._engines['espeak'] = espeak_engine
            
            self._initialized = len(self._engines) > 0
            return self._initialized
            
        except Exception as e:
            print(f"Failed to initialize TTS service: {e}")
            return False
    
    async def switch_engine(self, engine_name: str) -> bool:
        """切换TTS引擎"""
        if engine_name not in self._engines:
            return False
        
        self._current_engine = self._engines[engine_name]
        self._current_engine_name = engine_name
        return True
    
    def get_available_engines(self) -> List[str]:
        """获取可用的引擎列表"""
        return list(self._engines.keys())
    
    def get_current_engine(self) -> Optional[str]:
        """获取当前引擎名称"""
        return self._current_engine_name
    
    async def get_available_voices(self, engine_name: Optional[str] = None) -> List[VoiceProfile]:
        """获取可用语音列表"""
        engine = self._engines.get(engine_name) if engine_name else self._current_engine
        if engine:
            return await engine.get_available_voices()
        return []
    
    async def synthesize(
        self,
        text: str,
        voice_profile: Optional[VoiceProfile] = None,
        voice_settings: Optional[VoiceSettings] = None,
        output_format: str = 'wav',
        apply_effects: bool = False,
        effects_config: Optional[Dict[str, Any]] = None
    ) -> TTSResponse:
        """语音合成"""
        if not self._initialized or not self._current_engine:
            return TTSResponse(
                success=False,
                error_message="TTS service not initialized"
            )
        
        try:
            # 应用语音设置
            if voice_settings:
                self._voice_controller.settings = voice_settings
            
            # 处理文本
            processed_text = self._voice_controller.process_text(text)
            
            # 计算调整后的参数
            adjusted_rate = self._voice_controller.calculate_adjusted_rate(
                self._voice_controller.settings.rate, len(text)
            )
            adjusted_pitch = self._voice_controller.get_gender_adjusted_pitch(
                self._voice_controller.settings.pitch
            )
            
            # 创建合成请求
            # 获取格式，并确保是正确的 AudioFormat 类型
            from ..tts.base import AudioFormat
            
            # 尝试从设置中获取格式，如果不存在则使用 output_format
            format_value = self._voice_controller.settings.__dict__.get('format', output_format)
            
            # 如果格式值是字符串，转换为 AudioFormat 枚举
            if isinstance(format_value, str):
                try:
                    # 尝试转换为枚举值
                    format_enum = getattr(AudioFormat, format_value.upper())
                except (AttributeError, ValueError):
                    # 如果失败，使用默认的WAV格式
                    format_enum = AudioFormat.WAV
            else:
                # 已经是枚举或其他类型
                format_enum = format_value
            
            request = TTSRequest(
                text=processed_text,
                voice_profile=voice_profile,
                rate=adjusted_rate,
                volume=self._voice_controller.settings.volume,
                pitch=adjusted_pitch,
                format=format_enum
            )
            
            # 执行语音合成
            response = await self._current_engine.synthesize(request)
            
            if not response.success or not response.audio_data:
                return response
            
            # 应用音频效果
            if apply_effects and effects_config:
                response.audio_data = self._processor.apply_effects(
                    response.audio_data, effects_config
                )
            
            # 格式转换（如果需要）
            if request.format.value != output_format.lower():
                try:
                    response.audio_data = self._converter.convert_format(
                        response.audio_data,
                        request.format.value,
                        output_format.lower()
                    )
                except Exception as e:
                    print(f"Format conversion failed: {e}")
            
            return response
            
        except Exception as e:
            return TTSResponse(
                success=False,
                error_message=f"Synthesis failed: {str(e)}"
            )
    
    async def synthesize_audiobook(
        self,
        chapters: List[Dict[str, Any]],
        voice_profile: Optional[VoiceProfile] = None,
        voice_settings: Optional[VoiceSettings] = None,
        output_format: str = 'mp3'
    ) -> Dict[str, Any]:
        """合成有声读物"""
        if not self._initialized:
            return {"success": False, "error": "TTS service not initialized"}
        
        try:
            results = []
            total_duration = 0.0
            
            for i, chapter in enumerate(chapters):
                chapter_text = chapter.get('text', '')
                chapter_title = chapter.get('title', f'Chapter {i+1}')
                
                # 合成章节
                response = await self.synthesize(
                    text=chapter_text,
                    voice_profile=voice_profile,
                    voice_settings=voice_settings,
                    output_format=output_format
                )
                
                if response.success:
                    results.append({
                        'chapter': i + 1,
                        'title': chapter_title,
                        'audio_data': response.audio_data,
                        'duration': response.duration,
                        'metadata': response.metadata
                    })
                    total_duration += response.duration or 0.0
                else:
                    return {
                        "success": False,
                        "error": f"Failed to synthesize chapter {i+1}: {response.error_message}"
                    }
            
            return {
                "success": True,
                "chapters": results,
                "total_duration": total_duration,
                "chapter_count": len(chapters),
                "format": output_format
            }
            
        except Exception as e:
            return {"success": False, "error": f"Audiobook synthesis failed: {str(e)}"}
    
    async def set_voice_preset(self, preset_name: str) -> bool:
        """设置语音预设"""
        return self._voice_controller.apply_preset(preset_name)
    
    def get_voice_presets(self) -> Dict[str, VoiceSettings]:
        """获取语音预设"""
        return self._voice_controller.get_presets()
    
    async def create_custom_voice_preset(
        self, 
        name: str, 
        settings: VoiceSettings
    ) -> bool:
        """创建自定义语音预设"""
        return self._voice_controller.create_custom_preset(name, settings)
    
    async def optimize_for_content_type(self, content_type: str) -> str:
        """根据内容类型优化语音设置"""
        return self._voice_controller.optimize_for_content_type(content_type)
    
    async def get_audio_info(self, audio_data: bytes) -> Dict[str, Any]:
        """获取音频信息"""
        return self._processor.get_audio_info(audio_data)
    
    async def batch_synthesize(
        self,
        text_list: List[str],
        voice_profile: Optional[VoiceProfile] = None,
        voice_settings: Optional[VoiceSettings] = None,
        output_format: str = 'wav'
    ) -> List[TTSResponse]:
        """批量语音合成"""
        if not self._initialized:
            return [TTSResponse(success=False, error_message="TTS service not initialized")]
        
        tasks = []
        for text in text_list:
            task = self.synthesize(
                text=text,
                voice_profile=voice_profile,
                voice_settings=voice_settings,
                output_format=output_format
            )
            tasks.append(task)
        
        return await asyncio.gather(*tasks, return_exceptions=True)
    
    async def cleanup(self):
        """清理资源"""
        for engine in self._engines.values():
            await engine.cleanup()
        
        self._engines.clear()
        self._current_engine = None
        self._current_engine_name = None
        self._initialized = False
    
    @property
    def is_initialized(self) -> bool:
        """是否已初始化"""
        return self._initialized
    
    @property
    def voice_controller(self) -> VoiceController:
        """获取语音控制器"""
        return self._voice_controller


# 全局TTS服务实例
tts_service = TTSService()
